package com.ocean.security;

import com.ocean.core.util.StringUtil;
import com.ocean.security.properties.SuperAdminProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Set;

/**
 * 自定义权限验证
 * <p>
 * 也可以用hasAnyAuthority
 *
 * @author zhang
 * @since 2022-8-20
 */
@Service(value = "ss")
public class PermissionService {

    @Autowired
    protected SuperAdminProperties adminProperties;

    /**
     * 所有权限标识
     */
    protected static final String ALL_PERMISSION = "*:*:*";

    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermission(String permission) {
        if (StringUtil.isNull(permission)) {
            return false;
        }
        UserDetails sysUserTo = current();
        if (sysUserTo == null || CollectionUtils.isEmpty(sysUserTo.getAuthorities())) {
            return false;
        }
        Set<String> setPermission = AuthorityUtils.authorityListToSet(sysUserTo.getAuthorities());
        return hasPermissions(setPermission, permission);
    }

    /**
     * 判断是否包含权限
     *
     * @param permissions 权限列表
     * @param permission  权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermissions(Set<String> permissions, String permission) {
        return permissions.contains(ALL_PERMISSION) || permissions.contains(permission.trim());
    }

    /**
     * 是否是管理员或全部权限
     *
     * @return true是
     */
    public boolean hasAdmin() {
        UserDetails current = current();
        if (current != null && CollectionUtils.isEmpty(current.getAuthorities())) {
            Set<String> setPermission = AuthorityUtils.authorityListToSet(current.getAuthorities());
            return hasPermissions(setPermission, ALL_PERMISSION);
        }
        return false;
    }

    protected UserDetails current() {
        return (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}
